package com.dctp.common.db;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import java.util.List;

public class DictionaryDb {
    /**
     * 根据主键ID查询
     */
    public static Record findById(Long id) {
        return Db.findFirst("SELECT * FROM dctp_dictionary WHERE id = ?", id);
    }

    /**
     * 根据code查询单条
     */
    public static Record findByCode(String code) {
        return Db.findFirst("SELECT * FROM dctp_dictionary WHERE dict_code = ?", code);
    }

    /**
     * 查询所有字典项（可加缓存）
     */
    public static List<Record> findAll() {
        return Db.find("SELECT * FROM dctp_dictionary ORDER BY sort ASC, id ASC");
    }

    /**
     * 根据 dict_type 获取所有记录，返回 Record，key=code，value=value
     */
    public static Record findMapByType(String dictType) {
        List<Record> list = Db.find("SELECT dict_code, dict_value FROM dctp_dictionary WHERE dict_type = ? AND status = 1", dictType);
        Record result = new Record();
        for (Record r : list) {
            result.set(r.getStr("dict_code"), r.getStr("dict_value"));
        }
        return result;
    }

    /**
     * 根据 dict_code 返回 dict_value
     */
    public static String getValueByCode(String dictCode) {
        Record r = Db.findFirst("SELECT dict_value FROM dctp_dictionary WHERE dict_code = ? AND status = 1", dictCode);
        return r != null ? r.getStr("dict_value") : null;
    }

    /**
     * 根据多个 dict_code 返回 Record（key=dict_code, value=dict_value）
     */
    public static Record getValuesByCodes(String... dictCodes) {
        if (dictCodes == null || dictCodes.length == 0) return new Record();
        StringBuilder sql = new StringBuilder("SELECT dict_code, dict_value FROM dctp_dictionary WHERE status=1 AND dict_code IN (");
        for (int i = 0; i < dictCodes.length; i++) {
            sql.append("?");
            if (i < dictCodes.length - 1) sql.append(",");
        }
        sql.append(")");
        List<Record> list = Db.find(sql.toString(), (Object[])dictCodes);
        Record result = new Record();
        for (Record r : list) {
            result.set(r.getStr("dict_code"), r.getStr("dict_value"));
        }
        return result;
    }
}
